package cn.ximart.passport.service.impl;

import cn.ximart.passport.ex.ServiceException;
import cn.ximart.passport.mapper.RoleMapper;
import cn.ximart.passport.pojo.dto.RoleAddNewDTO;
import cn.ximart.passport.pojo.entity.Role;
import cn.ximart.passport.pojo.vo.RoleListItemVO;
import cn.ximart.passport.service.IRoleService;
import cn.ximart.passport.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void addNew(RoleAddNewDTO roleAddNewDTO) {
        log.debug("开始执行增加新角色的操作");
        String name = roleAddNewDTO.getName();
        int row = roleMapper.countByName(name);
        if(row>0){
            String message = "该角色名["+name+"]已存在，请换一个再尝试";
            throw new ServiceException(ServiceCode.ERR_EXISTED,message);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewDTO,role);
        role.setSort(0);

        int count = roleMapper.insert(role);
        if(count!=1){
            String message = "增加角色名失败，请稍后再尝试";
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始执行根据id删除角色的操作");
        int row = roleMapper.deleteById(id);
        if(row!=1){
            String message = "删除角色名失败，请稍后再尝试";
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,message);
        }
    }


    @Override
    public List<RoleListItemVO> list() {
        log.debug("开始执行查询角色列表的操作");
        List<RoleListItemVO> list = roleMapper.list();
        return list;
    }
}
